import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react';
import { FixedSizeList } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { motion } from 'framer-motion';

const List = FixedSizeList as any

const treeData = [
    {

        cmd: 'if',
        target: '10 > 0',
        value: '',
        children: [
            {
                cmd: 'click',
                target: 'button',
                value: '',
            }
        ],
    },
    {

        cmd: 'elseif',
        target: '10 > ',
        value: '',
        children: [
            {
                cmd: 'click',
                target: 'button',
                value: '',
            }
        ],
    },
    {
        cmd: 'else',
        target: '',
        value: '',
        children: [
            {
                cmd: 'click',
                target: 'button',
                value: '',
            }
        ],
    },
    {
        cmd: 'times',
        target: '10',
        value: '',
        children: [
            {
                cmd: 'click',
                target: 'button',
                value: '',
            }
        ],
    },
    {
        cmd: 'while',
        target: '10 > 0',
        value: '',
        children: [],
    }
]

// 初始扁平化树结构数据（精简示例）
const initialTreeData = {
    rootIds: [1, 10],
    items: {
        1: { id: 1, cmd: 'if', children: [2, 3], parentId: null, depth: 0 },
        2: { id: 2, cmd: 'if', children: [4], parentId: 1, depth: 1 },
        3: { id: 3, cmd: 'if', children: [5, 6], parentId: 1, depth: 1 },
        4: { id: 4, cmd: 'if', children: [7, 8], parentId: 2, depth: 2 },
        5: { id: 5, cmd: '市场策划', children: [], parentId: 3, depth: 2 },
        6: { id: 6, cmd: '品牌推广', children: [], parentId: 3, depth: 2 },
        7: { id: 7, cmd: 'React小组', children: [], parentId: 4, depth: 3 },
        8: { id: 8, cmd: 'Vue小组', children: [], parentId: 4, depth: 3 },
        10: { id: 10, cmd: 'if', children: [11], parentId: null, depth: 0 },
        11: { id: 11, cmd: '会计组', children: [], parentId: 10, depth: 1 },
    }
};

// 拖拽类型常量
const ItemTypes = {
    TREE_NODE: 'tree_node',
};

// 树操作工具函数
const TreeUtils = {

    // 添加节点
    addNode: (tree: any, parentId: string | null, newNode: any) => {
        if (!parentId) {
            return {
                ...tree,
                items: {
                    ...tree.items,
                    [newNode.id]: {
                        ...newNode,
                        depth: 0,
                        children: [],
                        parentId
                    }
                }
            };
        }
        const parent = tree.items[parentId];
        return {
            ...tree,
            items: {
                ...tree.items,
                [newNode.id]: {
                    ...newNode,
                    depth: parent.depth + 1,
                    children: [],
                    parentId
                },
                [parentId]: {
                    ...parent,
                    children: [...parent.children, newNode.id]
                }
            }
        };
    },

    // 删除节点（递归删除所有子节点）
    deleteNode: (tree: any, nodeId: string) => {
        const deleteRecursive = (items: any, id: string) => {
            const { children } = items[id];
            let newItems = { ...items };

            children.forEach((childId: string) => {
                newItems = deleteRecursive(newItems, childId);
            });

            // 从父节点的children中移除当前节点
            if (items[id].parentId !== null) {
                const parentId = items[id].parentId;
                const parent = newItems[parentId];
                newItems = {
                    ...newItems,
                    [parentId]: {
                        ...parent,
                        children: parent.children.filter((child: string) => child !== id)
                    }
                };
            }

            // 删除当前节点
            const { [id]: _, ...remainingItems } = newItems;
            return remainingItems;
        };

        const newItems = deleteRecursive(tree.items, nodeId);

        return {
            ...tree,
            rootIds: tree.rootIds.filter((id: string) => id !== nodeId),
            items: newItems
        };
    },
    // 更新节点
    updateNode: (tree: any, nodeId: string, updates: any) => {
        const node = tree.items[nodeId];
        if (!node) return tree;

        return {
            ...tree,
            items: {
                ...tree.items,
                [nodeId]: { ...node, ...updates }
            }
        };
    },

    // 移动节点（新增拖拽功能支持）
    moveNode: (tree: any, dragId: string, hoverId: string, position: string) => {
        // 不能将节点拖到自己身上
        if (dragId === hoverId) {
            console.warn("不能将节点拖到自己身上");
            return tree;
        }

        const dragItem = tree.items[dragId];
        const hoverItem = tree.items[hoverId];

        // 检查是否试图将父节点拖到子节点上
        if (TreeUtils.isDescendant(tree, dragId, hoverId,)) {
            console.warn("不能将节点移动到自己的子节点中");
            return tree;
        }

        // 记录原始父节点ID
        const originalParentId = dragItem.parentId;

        // 新的父节点取决于放置位置
        let newParentId;
        let newDepth;

        if (position === 'inside') {
            // 放在目标节点内部（成为其子节点）
            newParentId = hoverId;
            newDepth = hoverItem.depth + 1;
        } else {
            // 作为同级节点（放在目标节点之前或之后）
            newParentId = hoverItem.parentId;
            newDepth = hoverItem.depth;
        }

        // 创建节点的新版本
        const updatedItems = {
            ...tree.items,
            [dragId]: {
                ...dragItem,
                parentId: newParentId,
                depth: newDepth
            },
        };

        if (originalParentId) {
            // 1. 从原父节点中移除
            updatedItems[originalParentId] = {
                ...updatedItems[originalParentId],
                children: updatedItems[originalParentId].children.filter((id: string) => id !== dragId)
            }
        }

        if (newParentId) {
            // 2. 添加到新父节点
            const newParent = updatedItems[newParentId];
            let newChildren = [...newParent.children];

            // 确定新位置
            if (position === 'before') {
                // 放在目标节点之前
                const hoverIndex = newParent.children.indexOf(hoverId);
                newChildren.splice(hoverIndex, 0, dragId);
            } else if (position === 'after') {
                // 放在目标节点之后
                const hoverIndex = newParent.children.indexOf(hoverId);
                newChildren.splice(hoverIndex + 1, 0, dragId);
            } else if (position === 'inside') {
                // 成为目标节点的第一个子节点
                newChildren = [dragId, ...newParent.children];
            }

            updatedItems[newParent.id] = {
                ...newParent,
                children: newChildren
            }
        }

        // 4. 更新被移动节点所有子节点的深度
        TreeUtils.updateChildrenDepth(updatedItems, dragId, newDepth);

        // 5. 处理根节点变化
        let newRootIds = [...tree.rootIds];

        // 如果原来在根节点，但现在有了父节点，从根节点移除
        if (originalParentId === null && newParentId !== null) {
            newRootIds = newRootIds.filter(id => id !== dragId);
        }

        // 如果没有父节点（成为根节点）并且不在根节点列表中，则添加
        if (newParentId === null && !newRootIds.includes(dragId)) {
            newRootIds.push(dragId);
        }

        return {
            ...tree,
            rootIds: newRootIds,
            items: updatedItems
        };
    },

    // 检查一个节点是否是另一个节点的后代
    isDescendant: (tree: any, parentId: string, childId: string) => {
        let currentId = childId;

        while (currentId !== null) {
            const currentNode = tree.items[currentId];
            if (!currentNode) return false;
            if (currentNode.parentId === parentId) return true;
            currentId = currentNode.parentId;
        }

        return false;
    },

    // 递归更新所有子节点的深度
    updateChildrenDepth: (items: any, nodeId: string, baseDepth: number) => {
        const node = items[nodeId];
        if (!node || !node.children) return;

        node.children.forEach((childId: string) => {
            items[childId] = {
                ...items[childId],
                depth: baseDepth + 1
            };
            TreeUtils.updateChildrenDepth(items, childId, baseDepth + 1);
        });
    },

    //  将扁平化结构还原为嵌套树结构
    convertToNestedTree: (tree: any) => {
        // 辅助函数：将单个节点转换为嵌套格式
        const convertNode = (id: string) => {
            const node = tree.items[id];
            if (!node) return null;

            const children = node.children
                .map((childId: string) => convertNode(childId))
                .filter(Boolean);

            return {
                ...node,
                children: children.length ? children : undefined
            };
        };

        // 处理根节点
        const roots = tree.rootIds
            .map((rootId: string) => convertNode(rootId))
            .filter(Boolean);

        return roots;
    },

    //  格式化输出数据结构
    formatDataForDisplay: (data: any) => {
        try {
            return JSON.stringify(data, null, 2);
        } catch {
            return "无法格式化数据";
        }
    }
};

const TreeItem = React.memo(({
    node,
    index,
    style,
    selectedIndex,
    setSelectedId,
    editingId,
    setEditingId,
    editValue,
    setEditValue,
    onToggleExpand,
    expandedIds,
    onAdd,
    onDelete,
    onStartEdit,
    onDropNode,
    onEditComplete
}: any) => {
    const ref = useRef(null);
    const [hoverType, setHoverType] = useState<string | null>(null); // 'inside', 'before', 'after'

    const [{ isDragging }, drag] = useDrag(() => ({
        type: ItemTypes.TREE_NODE,
        item: { id: node.id, cmd: node.cmd, depth: node.depth },
        collect: (monitor) => ({
            isDragging: !!monitor.isDragging(),
        }),
    }));

    const [{ isOver }, drop] = useDrop(() => ({
        accept: ItemTypes.TREE_NODE,
        drop: (item: { id: string; cmd: string; depth: number }, monitor: any) => {
            // 确定放置位置
            const offset = monitor.getClientOffset();
            const el: any = ref.current;
            if (!el || !offset) return;

            const rect = el.getBoundingClientRect();
            const middleY = rect.top + rect.height / 2;
            const quarterY1 = rect.top + rect.height / 4;
            const quarterY3 = rect.top + rect.height * 3 / 4;
            // 根据鼠标位置判断放置位置
            let position;
            if (offset.y < quarterY1) {
                position = 'before';
            } else if (offset.y > quarterY3) {
                position = 'after';
            } else {
                position = 'inside';
            }

            onDropNode(item.id, node.id, position);
        },
        hover: (item: { id: string; cmd: string; depth: number }, monitor) => {
            const offset = monitor.getClientOffset();
            const el: any = ref.current;
            if (!el || !offset) return;

            const rect = el.getBoundingClientRect();
            const middleY = rect.top + rect.height / 2;
            const quarterY1 = rect.top + rect.height / 4;
            const quarterY3 = rect.top + rect.height * 3 / 4;

            // 根据鼠标位置更新放置指示器
            if (offset.y < quarterY1) {
                setHoverType('before');
            } else if (offset.y > quarterY3) {
                setHoverType('after');
            } else {
                setHoverType('inside');
            }
        },
        collect: (monitor) => ({
            isOver: !!monitor.isOver(),
        }),
    }));

    drag(drop(ref));

    return (
        <div
            ref={ref}
            style={{
                ...style,
                position: 'relative',
                opacity: isDragging ? 0.5 : 1,
                cursor: isDragging ? 'grabbing' : 'grab'
            }}
        >
            {/* 拖拽指示器（只在拖拽时显示） */}
            {isOver && hoverType && (
                <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: 3, opacity: 1 }}
                    className="drop-indicator"
                    style={{
                        position: 'absolute',
                        left: node.depth * 24,
                        right: 10,
                        backgroundColor: hoverType === 'inside' ? '#4caf50' : '#2196f3',
                        zIndex: 100,
                        borderRadius: 2,
                        ...(hoverType === 'before' ? { top: 0 } :
                            hoverType === 'after' ? { bottom: 0 } :
                                { top: '50%', height: 4, marginTop: -2, left: 20 })
                    }}
                />
            )}

            <div
                style={{
                    marginLeft: `${node.depth * 24}px`,
                    display: 'flex',
                    alignItems: 'center',
                    backgroundColor: selectedIndex === node.id ? '#e3f2fd' : 'white',
                    borderBottom: '1px solid #eee',
                    transition: 'background-color 0.2s',
                    transform: isDragging ? 'scale(1.02)' : 'none',
                    boxShadow: isDragging ? '0 4px 8px rgba(0,0,0,0.1)' : 'none',
                    zIndex: isDragging ? 100 : 1,
                    borderRadius: 4,
                    padding: '8px 10px',
                }}
                onClick={() => setSelectedId(node.id)}
            >
                {/* 展开/折叠图标 */}
                {['if', 'elseif', 'else', 'while', 'do', 'times'].includes(node.cmd) ? (
                    <div
                        style={{
                            marginRight: 8,
                            transform: expandedIds.has(node.id) ? 'rotate(0deg)' : 'rotate(-90deg)',
                            transition: 'transform 0.2s',
                            fontSize: 20,
                            cursor: 'pointer'
                        }}
                        onClick={(e) => {
                            e.stopPropagation();
                            onToggleExpand(node.id);
                        }}
                    >
                        {expandedIds.has(node.id) ? '▼' : '▶'}
                    </div>
                ) : (
                    <div style={{ width: 28 }} />
                )}

                {/* 节点内容 */}
                {editingId === node.id ? (
                    <input
                        type="text"
                        value={editValue}
                        onChange={e => setEditValue(e.target.value)}
                        onBlur={() => onEditComplete()}
                        onKeyDown={e => e.key === 'Enter' && onEditComplete()}
                        autoFocus
                        style={{ flex: 1, padding: 4, border: '1px solid #64b5f6' }}
                        onClick={e => e.stopPropagation()}
                    />
                ) : (
                    <div
                        style={{ flex: 1, padding: '8px 0' }}
                        onDoubleClick={() => onStartEdit(node.id, node.cmd)}
                    >
                        {node.cmd}
                    </div>
                )}

                {/* 操作按钮 */}
                <div style={{ display: 'flex', gap: 8 }}>
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            onAdd(node.id);
                        }}
                        title="添加子节点"
                    >
                        +
                    </button>
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            onDelete(node.id);
                        }}
                        title="删除节点"
                    >
                        ×
                    </button>
                </div>
            </div>
        </div>
    );
});

const EmptyTreeItem = React.memo(({
    node,
    index,
    style,
    selectedIndex,
    setSelectedId,
    editingId,
    setEditingId,
    editValue,
    setEditValue,
    onToggleExpand,
    expandedIds,
    onAdd,
    onDelete,
    onStartEdit,
    onDropNode,
    onEditComplete
}: any) => {
    const ref = useRef(null);
    const [hoverType, setHoverType] = useState<string | null>(null); // 'inside', 'before', 'after'

    const [{ isOver }, drop] = useDrop(() => ({
        accept: ItemTypes.TREE_NODE,
        drop: (item: { id: string; cmd: string; depth: number }, monitor: any) => {
            // 确定放置位置
            const offset = monitor.getClientOffset();
            const el: any = ref.current;
            if (!el || !offset) return;

            const rect = el.getBoundingClientRect();
            const middleY = rect.top + rect.height / 2;
            const quarterY1 = rect.top + rect.height / 4;
            const quarterY3 = rect.top + rect.height * 3 / 4;
            // 根据鼠标位置判断放置位置
            let position;
            if (offset.y < quarterY1) {
                position = 'before';
            } else if (offset.y > quarterY3) {
                position = 'after';
            } else {
                position = 'inside';
            }

            onDropNode(item.id, node.id, position);
        },
        hover: (item: { id: string; cmd: string; depth: number }, monitor) => {
            const offset = monitor.getClientOffset();
            const el: any = ref.current;
            if (!el || !offset) return;

            const rect = el.getBoundingClientRect();
            const middleY = rect.top + rect.height / 2;
            const quarterY1 = rect.top + rect.height / 4;
            const quarterY3 = rect.top + rect.height * 3 / 4;

            // 根据鼠标位置更新放置指示器
            if (offset.y < quarterY1) {
                setHoverType('before');
            } else if (offset.y > quarterY3) {
                setHoverType('after');
            } else {
                setHoverType('inside');
            }
        },
        collect: (monitor) => ({
            isOver: !!monitor.isOver(),
        }),
    }));

    return (
        <div
            ref={(node: any) => {
                ref.current = node
                drop(ref)
            }}
            style={{
                ...style,
                position: 'relative',

            }}
        >
            {/* 拖拽指示器（只在拖拽时显示） */}
            {isOver && hoverType && (
                <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: 3, opacity: 1 }}
                    className="drop-indicator"
                    style={{
                        position: 'absolute',
                        left: node.depth * 24,
                        right: 10,
                        backgroundColor: hoverType === 'inside' ? '#4caf50' : '#2196f3',
                        zIndex: 100,
                        borderRadius: 2,
                        ...(hoverType === 'before' ? { top: 0 } :
                            hoverType === 'after' ? { bottom: 0 } :
                                { top: '50%', height: 4, marginTop: -2, left: 20 })
                    }}
                />
            )}
            <div
                style={{
                    marginLeft: `${node.depth * 24}px`,
                    display: 'flex',
                    alignItems: 'center',
                    backgroundColor: selectedIndex === node.id ? '#e3f2fd' : 'white',
                    borderBottom: '1px solid #eee',
                    transition: 'background-color 0.2s',
                    transform: 'none',
                    boxShadow: 'none',
                    zIndex: 1,
                    borderRadius: 4,
                    padding: '8px 10px',
                }}
                onClick={() => setSelectedId(node.id)}
            >
                {/* 操作按钮 */}
                <div style={{ display: 'flex', gap: 8 }}>
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            onAdd(node.id);
                        }}
                        title="添加节点"
                    >
                        添加节点
                    </button>
                </div>
            </div>
        </div>
    );
});

const TreeComponent = () => {

    const [treeData, setTreeData] = useState<any>(initialTreeData);
    const [expandedIds, setExpandedIds] = useState<any>(new Set([1, 10]));
    const [selectedIndex, setSelectedId] = useState(null);
    const [editingId, setEditingId] = useState<string | null>(null);
    const [editValue, setEditValue] = useState('');

    // 获取所有可见节点（扁平化列表）
    const visibleNodes = useMemo(() => {
        const result: any[] = [];

        const traverse = (id: string) => {
            const node = treeData.items[id];
            if (!node) return;

            result.push(node);

            if (expandedIds.has(id)) {
                if (node.children.length > 0) {
                    node.children.forEach((childId: string) => traverse(childId));
                } else {
                    result.push({
                        id: Date.now() + Math.random(),
                        cmd: 'add',
                        children: [],
                        parentId: node.id,
                        depth: node.depth + 1
                    });
                }
            }
        }

        treeData.rootIds.forEach((id: string) => traverse(id));
        result.push({
            id: Date.now() + Math.random(),
            cmd: 'add',
            children: [],
            parentId: null,
            depth: 0
        })
        return result;
    }, [treeData, expandedIds]);


    // 添加节点
    const handleAdd = useCallback((parentId: string | null) => {
        setTreeData((prev: any) => {
            const newNode = {
                id: Date.now() + Math.floor(Math.random() * 1000),
                cmd: `新节点_${Math.floor(Math.random() * 100)}`,
                children: []
            };

            return TreeUtils.addNode(prev, parentId, newNode);
        });

        if (parentId) {
            setExpandedIds((prev: any) => new Set(prev).add(parentId));
        }
    }, []);

    // 删除节点
    const handleDelete = useCallback((nodeId: string) => {
        setTreeData((prev: any) => TreeUtils.deleteNode(prev, nodeId));
        setSelectedId(null);
    }, []);

    // 开始编辑
    const handleEditStart = useCallback((id: string, cmd: string) => {
        setEditingId(id);
        setEditValue(cmd);
    }, []);

    // 完成编辑
    const handleEditComplete = useCallback(() => {
        if (editingId && editValue.trim() !== '') {
            setTreeData((prev: any) => TreeUtils.updateNode(prev, editingId, { cmd: editValue }));
        }
        setEditingId(null);
        setEditValue('');
    }, [editingId, editValue]);

    // 切换节点展开状态
    const toggleExpand = useCallback((id: string) => {
        setExpandedIds((prev: any) => {
            const newSet = new Set(prev);
            if (prev.has(id)) {
                newSet.delete(id);
            } else {
                newSet.add(id);
            }
            return newSet;
        });
    }, []);

    // 处理节点放置
    const handleDrop = useCallback((dragId: string, hoverId: string, position: string) => {
        setTreeData((prev: any) => TreeUtils.moveNode(prev, dragId, hoverId, position));
    }, []);

    // 为每个节点创建拖拽组件
    const renderTreeNode = useCallback(({ index, style }: any) => {
        const node = visibleNodes[index];
        if (node.cmd === 'add') {
            return <EmptyTreeItem
                node={node}
                index={index}
                style={{}}
                selectedIndex={selectedIndex}
                setSelectedId={setSelectedId}
                editingId={editingId}
                setEditingId={setEditingId}
                editValue={editValue}
                setEditValue={setEditValue}
                onToggleExpand={toggleExpand}
                expandedIds={expandedIds}
                onAdd={handleAdd}
                onDelete={handleDelete}
                onStartEdit={handleEditStart}
                onDropNode={handleDrop}
                onEditComplete={handleEditComplete}
            />
        }
        return (
            <TreeItem
                node={node}
                index={index}
                style={{}}
                selectedIndex={selectedIndex}
                setSelectedId={setSelectedId}
                editingId={editingId}
                setEditingId={setEditingId}
                editValue={editValue}
                setEditValue={setEditValue}
                onToggleExpand={toggleExpand}
                expandedIds={expandedIds}
                onAdd={handleAdd}
                onDelete={handleDelete}
                onStartEdit={handleEditStart}
                onDropNode={handleDrop}
                onEditComplete={handleEditComplete}
            />
        );
    }, [
        visibleNodes,
        selectedIndex,
        editingId,
        editValue,
        expandedIds,
        toggleExpand,
        handleAdd,
        handleDelete,
        handleEditStart,
        handleDrop
    ]);

    return (
        <DndProvider backend={HTML5Backend}>
            <div style={{
                width: '100%',
                height: '100vh',
                display: 'flex',
                flexDirection: 'column',
                fontFamily: 'Arial, sans-serif',
                color: '#000'
            }}>
                <div style={{
                    padding: 20,
                    backgroundColor: '#2196f3',
                    color: 'white',
                    fontSize: 24,
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}>
                    组织结构树（带拖拽功能）
                </div>
                <div style={{
                    flex: 1,
                    display: 'flex',
                    padding: 20,
                    gap: 20,
                }}>
                    {/* 左侧树形结构区域 */}
                    <div style={{
                        flex: 1,
                        border: '1px solid #e0e0e0',
                        borderRadius: 8,
                        overflow: 'hidden',
                        boxShadow: '0 4px 8px rgba(0,0,0,0.05)',
                        display: 'flex',
                        flexDirection: 'column'
                    }}>
                        <div style={{
                            padding: 16,
                            backgroundColor: '#f5f5f5',
                            borderBottom: '1px solid #e0e0e0',
                            fontWeight: 'bold',
                            color: '#2196f3',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between'
                        }}>
                            <div>组织结构树 - {Object.keys(treeData.items).length}个节点</div>
                            <div style={{ fontSize: 14, fontWeight: 'normal', color: '#666' }}>
                                拖拽节点重新排列位置
                            </div>
                        </div>
                        <div style={{ flex: 1, overflow: 'hidden' }} >
                            <AutoSizer>
                                {({ height, width }) => (<div>
                                    <List
                                        height={height}
                                        width={width}
                                        itemCount={visibleNodes.length}
                                        itemSize={50}
                                    >
                                        {renderTreeNode}
                                    </List>
                                </div>
                                )}
                            </AutoSizer>
                        </div>
                    </div>

                    {/* 右侧操作面板 */}
                    <div style={{
                        width: 300,
                        display: 'flex',
                        flexDirection: 'column',
                        gap: 20
                    }}>
                        <div style={{
                            border: '1px solid #e0e0e0',
                            borderRadius: 8,
                            padding: 16,
                            boxShadow: '0 4px 8px rgba(0,0,0,0.05)',
                            backgroundColor: '#fff'
                        }}>
                            <h3 style={{ marginTop: 0, marginBottom: 15, color: '#2196f3' }}>操作指南</h3>

                            <div style={{
                                marginBottom: 15,
                                padding: 12,
                                backgroundColor: '#f0f8ff',
                                borderRadius: 6
                            }}>
                                <strong>拖拽功能：</strong>
                                <ul style={{ paddingLeft: 20, margin: '8px 0' }}>
                                    <li>拖到节点上方 - 放入节点内部</li>
                                    <li>拖到节点顶部1/4区域 - 放在节点前</li>
                                    <li>拖到节点底部1/4区域 - 放在节点后</li>
                                </ul>
                            </div>

                            <div style={{
                                display: 'flex',
                                gap: 10,
                                flexWrap: 'wrap'
                            }}>
                                <button
                                    style={{
                                        padding: '10px 15px',
                                        backgroundColor: '#4caf50',
                                        color: 'white',
                                        border: 'none',
                                        borderRadius: 4,
                                        cursor: 'pointer',
                                        flex: 1
                                    }}
                                    onClick={() => handleAdd(null)}
                                >
                                    添加根节点
                                </button>

                                <button
                                    style={{
                                        padding: '10px 15px',
                                        backgroundColor: '#ff9800',
                                        color: 'white',
                                        border: 'none',
                                        borderRadius: 4,
                                        cursor: 'pointer',
                                        flex: 1
                                    }}
                                    onClick={() => {
                                        setExpandedIds(new Set(treeData.rootIds));
                                    }}
                                >
                                    展开全部
                                </button>
                            </div>

                            <div style={{
                                marginTop: 15,
                                padding: 12,
                                backgroundColor: '#fff8e1',
                                borderRadius: 6
                            }}>
                                <strong>当前选中节点：</strong>
                                <div>
                                    {selectedIndex ? (
                                        <>
                                            <div>{treeData.items[selectedIndex]?.cmd}</div>
                                            <div style={{ fontSize: 12, marginTop: 4 }}>
                                                深度: {treeData.items[selectedIndex]?.depth} |
                                                子节点: {treeData.items[selectedIndex]?.children.length}
                                            </div>
                                        </>
                                    ) : '未选择节点'}
                                </div>
                            </div>
                        </div>

                        <div style={{
                            border: '1px solid #e0e0e0',
                            borderRadius: 8,
                            padding: 16,
                            boxShadow: '0 4px 8px rgba(0,0,0,0.05)',
                            backgroundColor: '#fff'
                        }}>
                            <h3 style={{ marginTop: 0, marginBottom: 15, color: '#2196f3' }}>性能统计</h3>
                            <p>总节点数: {Object.keys(treeData.items).length}</p>
                            <p>可见节点: {visibleNodes.length}</p>
                            <p>展开节点: {expandedIds.size}</p>
                        </div>
                    </div>
                </div>
            </div>
        </DndProvider>
    );
};

export default TreeComponent;

// 添加一些CSS样式
const styles = `
  .tree-container {
    position: relative;
  }
  
  .drop-indicator {
    height: 3px;
    background-color: #2196f3;
    position: absolute;
    left: 0;
    right: 0;
    z-index: 100;
  }
  
  .drop-before {
    top: 0;
  }
  
  .drop-after {
    bottom: 0;
  }
  
  .drop-inside {
    top: 50%;
    height: 4px;
    margin-top: -2px;
    left: 20px;
    background-color: #4caf50;
  }
`;

// 将样式注入到文档中
const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);